package com.aounhui.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.aounhui.common.entity.Result;
import com.aounhui.common.utils.UUIDUtil;
import com.aounhui.customer.entity.Order;
import com.aounhui.customer.entity.OrderContent;
import com.aounhui.customer.mapper.OrderMapper;
import com.aounhui.customer.openfeign.ProductorService;
import com.aounhui.customer.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author aounhui
 * @version 1.0
 * @date 2021/6/16 16:52
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductorService productorService;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result buy(Order order) {
        log.info("{} 购买{},订单执行",order.getUserId(), order.getContents());
        Date orderTime = new Date();
        String orderId = UUIDUtil.getUUID();
        //订单多种商品，遍历处理
        StringBuffer commodityIds = new StringBuffer();
        boolean complete = true;
        float amountMoney = 0;
        List<List<Map<String, String>>> res = new ArrayList<>();
        for (OrderContent content : order.getContents()) {
            String commodityName = content.getCommodityName();
            int orderNumber = content.getNumber();
            //TODO 调用方异常，被调用方不回滚
            //订单金额
            Result commodityFactory = productorService.getCommodityFactory(commodityName);
            Map<String, Object> resultMap = (Map<String, Object>) commodityFactory.getContent();
            amountMoney += orderNumber * Float.parseFloat(resultMap.get("price").toString());
            //如果库存数量满足，直接给用户，并且从快过期的商品先处理，生产日期升序排序
            Result result = productorService.getCommodity(commodityName, orderNumber, orderId);
            List<Map<String, String>> commoditys = (List<Map<String, String>>) result.getContent();
            res.add(commoditys);
            commoditys.stream().forEach((commodityMap)->commodityIds.append(commodityMap.get("id")));
            //库存数量不满足订单数量
            if (commoditys.size() != orderNumber) {
                complete = false;
                //TODO 未完成队列
                log.warn("{}订单库存不足，不足内容加入队列");
            }
        }
        order.setAmountMoney(amountMoney);
        order.setOrderContent(JSON.toJSONString(order.getContents()));
        order.setCommodityIds(String.valueOf(commodityIds));
        order.setId(orderId);
        if (complete) {
            //订单完成，订单信息补充
            order.setCompleteTime(new Date());
            order.setExts("completed");
        } else {
            //订单未完成，订单信息不全
            order.setExts("no complete");
        }
        orderMapper.insertSelective(order);
        log.info("订单编号{}完成", orderId);
//        throw new SellCommodityException("模拟异常");
        return Result.ok(res);
    }
}
